﻿using System;
using System.Drawing;
using System.Linq;
using Styx;
using Styx.Helpers;
using Styx.Plugins.PluginClass;
using Styx.WoWInternals;
using Styx.WoWInternals.WoWObjects;

namespace FocusHelper
{
    public class FocusHelper : HBPlugin
    {
        public override Version Version { get { return new Version(1, 0); } }

        public override string Name { get { return "Focus Helper"; } }
        public override string Author { get { return "fiftypence"; } }
        public override bool WantButton { get { return true; } }

        public string mFocusName { get { return FocusHelperSettings.mInstance.mFocusName; } }

        public override void OnButtonPress()
        {
            var configUi = new Gui.NameInput(this);
            configUi.Show();
        }

        public override void Initialize()
        {
            FocusHelperSettings.mInstance.Load();

            Logging.Write(Color.Orange, "[FHelper] Focus Helper Loaded");
            PrintFocus();
        }

        public void PrintFocus()
        {
            var desiredName = mFocusName ?? "NULL";
            var focusName = StyxWoW.Me.FocusedUnit != null ? StyxWoW.Me.FocusedUnit.Name : "NULL";

            Logging.Write(Color.Orange, "[FHelper] Desired focus target is currently {0}", desiredName);
            Logging.Write(Color.Orange, "[FHelper] Actual focus target is currently {0}", focusName);
        }

        public override void Pulse()
        {
            if (mFocusName != null && (StyxWoW.Me.FocusedUnit == null || 
               (StyxWoW.Me.FocusedUnit != null && StyxWoW.Me.FocusedUnit.Name != mFocusName)))
            {
                var newFocus = ObjectManager.GetObjectsOfType<WoWUnit>(true, true).FirstOrDefault(unit => unit.Name == mFocusName);

                if (newFocus != null)
                {
                    // StyxWoW.Me.SetFocus(newFocus);
                    // Set focus sets the focus but doesn't display the WoW UI focus frame?
                    // /target focus ingame works fine. WTF.
                    // Will use Lua for now.

                    newFocus.Target();
                    Lua.DoString("FocusUnit(\"target\");");
                    StyxWoW.Me.TargetLastTarget();

                    Logging.Write(Color.Orange, "[FHelper] Focus changed to {0}", newFocus.Name);
                }
            }
        }
    }
}
